package com.example.ourradio;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;

/**
 * Activity which displays a login screen to the user, offering registration as
 * well.
 */
public class LoginActivity extends Activity {
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_login);

		// Set up the login form.
		findViewById(R.id.google_sign_in_button).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						attemptLoginViaGoogle();
					}
				});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		getMenuInflater().inflate(R.menu.login, menu);
		return true;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case 0:
			if (resultCode != RESULT_OK || data == null) {
				return;
			}
			// Get the token.
			String token = data.getStringExtra("token");
			
			finish();
				
			// Save preferences
			SharedPreferences settings = getSharedPreferences(
				Utils.PREFS_NAME, 0
			);
			SharedPreferences.Editor editor = settings.edit();
			editor.putString(Utils.OAUTH_TOKEN, token);
			editor.commit();
				
			Intent i = new Intent();
			i.setClassName(
				"com.example.ourradio", 
	           	"com.example.ourradio.MainActivity"
	        );
			startActivity(i);
			
			return;
		}
	    super.onActivityResult(requestCode, resultCode, data);
	}
	
	public void attemptLoginViaGoogle() {
		Intent intent = new Intent(this, LoginWebViewActivity.class);
	    intent.setData(Uri.parse(Utils.AUTHENTICATION_ENDPOINT));
	    startActivityForResult(intent, 0);
	}	
}
